import { useEffect } from 'react'
import { useRouter } from 'next/router'
import { useAppStore } from '@/store/app'
import Loading from '@/components/Loading'
import { checkVersion } from '@/lib/version'
import type { AppProps } from 'next/app'
import '../styles/globals.css'

function MyApp({ Component, pageProps }: AppProps) {
  const router = useRouter()
  const { setLoading, version, setVersion } = useAppStore()

  useEffect(() => {
    const initVersion = async () => {
      const currentVersion = await checkVersion()
      if (!version) {
        setVersion(currentVersion)
      } else if (version !== currentVersion) {
        window.location.reload()
      }
    }

    initVersion()

    // 路由变化时显示 loading
    const handleStart = () => setLoading(true)
    const handleComplete = () => setLoading(false)

    router.events.on('routeChangeStart', handleStart)
    router.events.on('routeChangeComplete', handleComplete)
    router.events.on('routeChangeError', handleComplete)

    return () => {
      router.events.off('routeChangeStart', handleStart)
      router.events.off('routeChangeComplete', handleComplete)
      router.events.off('routeChangeError', handleComplete)
    }
  }, [version, setVersion])

  return (
    <div className="app-container">
      <Loading />
      <Component {...pageProps} />
    </div>
  )
}

export default MyApp